<template>
	<view class="container">
		<v-tabs
			v-model="current"
			:tabs="tabs"
			@change="changeTab"
			:fixed="true"
		></v-tabs>
		<view v-if="tabName === '已接单'" class="order-tab-list">
			<v-tabs
				v-model="current2"
				:tabs="l2Tabs"
				@change="changeTab2"
				:fixed="true"
			></v-tabs>
		</view>
		<view v-if="isfetch">
			<view class="flex f-column" v-if="orderList.length > 0">
				<view
					class="goods-item flex f-column"
					v-for="(item, index) in orderList"
					:key="index"
				>
					<view class="firsttop">
						<view class="top-title firsttop-title"
							>订单号：{{ item.orderNumber }}</view
						>
						<view
							v-if="item.visitStatus == '0'"
							style="color: #3063d9; margin-top: 15rpx"
							>未接单</view
						>
						<view
							v-else-if="item.visitStatus == '1'"
							style="color: #3063d9; margin-top: 15rpx"
							>已接单</view
						>
						<view
							v-else-if="item.visitStatus == '2'"
							style="color: #3063d9; margin-top: 15rpx"
							>待送回</view
						>
						<view
							v-else="item.visitStatus == '3'"
							style="color: #3063d9; margin-top: 15rpx"
							>已完成</view
						>
					</view>
					<view class="top-title">上门时间：{{ item.visitDate }}</view>
					<view class="top-title">洗衣店名称：</view>
					<view class="top-title">洗衣店地址：</view>
					<view class="top-title">衣物数量：{{ item.goodsNumber }}</view>
					<view class="top-title">用户姓名：{{ item.userName }}</view>
					<view class="top-title">用户电话：{{ item.mobile }}</view>
					<view class="top-title"
						>用户地址：{{ item.province }}{{ item.city }}{{ item.area
						}}{{ item.visitAddress }}</view
					>

					<view class="bottom-column">
						<view
							class="top-jiedan"
							v-if="item.visitStatus == '0'"
							@click="updateVisitStatus(0, item, index)"
							>接单</view
						>
						<view
							class="top-jiedan"
							v-else-if="item.visitStatus == '1'"
							@click="updateVisitStatus(1, item, index)"
							>我要取衣物</view
						>
						<view
							class="top-jiedan"
							v-else-if="item.visitStatus == '2'"
							@click="updateVisitStatus(2, item, index)"
							>待送回</view
						>
						<view
							class="top-jiedan"
							v-else="item.visitStatus == '3'"
							@click="updateVisitStatus(3, item, index)"
							>已送回衣物</view
						>
					</view>
				</view>
				<uni-load-more ref="loadMore" :status="loadStatus"></uni-load-more>
			</view>
			<view class="flex f-column f-align" v-else>
				<text class="font36 gray999 bold mt50">暂无订单</text>
			</view>
		</view>
	</view>
</template>

<script>
import vTabs from '@/components/v-tabs/v-tabs.vue'
import loadMore from '@/components/uni-load-more/uni-load-more.vue'
let util = require('../../utils/util.js')

export default {
	data() {
		return {
			current: 0,
			tabs: ['任务大厅', '已接单'],
			page: 1,
			loadStatus: 'more',
			isfetch: false,
			orderList: [],
			orderState: '0',
			visitStatus: '',
			typeId: '',

			_discoveryStarted: false,
			devices: [],
			deviceId: '', // 模拟选择了一个打印机
			canWrite: false,
			_deviceId: '',
			_serviceId: '',
			_characteristicId: '',
			printData: null,
			current2: 0,
			// 1，2，3
			l2Tabs: ['待上门', '待送回', '已完成'],
			tabName: ''
		}
	},
	components: {
		vTabs,
		loadMore
	},
	onLoad(option) {
		this.current = option.tabs
	},
	onShow() {
		this.page = 1
		this.loadStatus = 'more'
		this.getOrderList()
	},
	onPullDownRefresh() {
		this.page = 1
		this.loadStatus = 'more'
		this.getOrderList()
		setTimeout(() => {
			uni.stopPullDownRefresh()
		}, 1000)
	},
	onReachBottom() {
		if (this.loadStatus != 'noMore') {
			this.loadStatus = 'loading'
			this.page += 1
			this.getOrderList()
		}
	},
	methods: {
		// visitStatus 上门取送状态0 未接单 1 已接单 2 待送回 3 已完成
		updateVisitStatus(status, item, index) {
			this.printData = JSON.parse(JSON.stringify(item))
			const { id } = item
			if (status == '0') {
				this.$http
					.ajax({
						url: '/Order/updateVisitStatus',
						params: {
							adminId: uni.getStorageSync('userInfo').id,
							visitStatus: '1',
							id
						}
					})
					.then((res) => {
						this.$api.msg('接单成功')
						if (res.code == 200) {
							this.orderList[index].visitStatus = '1'
						}
					})
			} else if (status == '1') {
				this.$http
					.ajax({
						url: '/Order/updateVisitStatus',
						params: {
							adminId: uni.getStorageSync('userInfo').id,
							visitStatus: '2',
							id
						}
					})
					.then((res) => {
						if (!this.canWrite) {
							this.openBluetoothAdapter()
						} else {
							this.printBarcode()
						}
						const tt = setTimeout(() => {
							this.$api.msg('取衣成功')
							if (res.code == 200) {
								this.orderList[index].visitStatus = '2'
							}
							clearTimeout(tt)
						}, 3 * 1000)
					})
			} else if (status == '2') {
				// this.openBluetoothAdapter()
				// this.$api.msg("待开发");
				this.$http
					.ajax({
						url: '/Order/updateVisitStatus',
						params: {
							adminId: uni.getStorageSync('userInfo').id,
							visitStatus: '3',
							id
						}
					})
					.then((res) => {
						this.$api.msg('已送回衣物')
						if (res.code == 200) {
							this.orderList[index].visitStatus = '3'
						}
					})
			} else if (status == '3') {
				// this.openBluetoothAdapter()
				// this.$api.msg("待开发");
			}
		},
		//打印条形码
		printBarcode() {
			if (!this.canWrite) {
				this.$api.msg('打印机连接异常, 请重新连接')
				return
			}
			console.log('可以打印啦！')
			let arrPrint = []
			//初始化打印机
			arrPrint.push(util.sendDirective([0x1b, 0x40])) //16进制
			//居中对齐
			arrPrint.push(util.sendDirective([0x1b, 0x61, 0x01])) //16进制
			//正文
			//Enable the barcode
			arrPrint.push(util.sendDirective([0x1d, 0x45, 0x43, 0x01]))
			//Set the barcode height is 100
			arrPrint.push(util.sendDirective([0x1d, 0x68, 0xb4]))
			//Set HRI character print location on bottom
			// arrPrint.push(util.sendDirective([0x1d, 0x48, 0x02]));
			// arrPrint.push(util.sendDirective([0x1d, 0x77, 0x02]));

			//0x1d,0x6b,0x49,最后的14为条码内容的长度，"test1234567890".length
			arrPrint.push(util.sendDirective([0x1d, 0x6b, 0x49, 14]))

			//test1234567890条码内容，目前是指令方式打印，最大支持14位数字
			arrPrint.push(util.hexStringToBuff(this.printData.orderNumber))
			// arrPrint.push(util.hexStringToBuff('1234567891231'));

			//恢复居左对齐
			arrPrint.push(util.sendDirective([0x1b, 0x61, 0x00])) //16进制

			arrPrint.push(
				util.hexStringToBuff(`用户昵称: ${this.printData.userName}\n`)
			)
			arrPrint.push(
				util.hexStringToBuff(`用户电话: ${this.printData.mobile}\n`)
			)
			arrPrint.push(util.hexStringToBuff(''))
			arrPrint.push(
				util.hexStringToBuff(`下单数量: ${this.printData.goodsNumber}\n`)
			)
			arrPrint.push(
				util.hexStringToBuff(`下单时间: ${this.printData.transactionTime}\n`)
			)
			arrPrint.push(
				util.hexStringToBuff(
					`下单地址: ${this.printData.province} ${this.printData.city} ${this.printData.area} ${this.printData.visitAddress}\n`
				)
			)

			// arrPrint.push(util.hexStringToBuff(`用户昵称: 他化自在\n`));
			// arrPrint.push(util.hexStringToBuff(`用户电话: 18339112554\n`));
			// arrPrint.push(util.hexStringToBuff(`下单数量: 3\n`));
			// arrPrint.push(util.hexStringToBuff(`下单时间: 2022-09-06 12:12:12\n`));
			// arrPrint.push(util.hexStringToBuff(`下单地址: 未来路绿都广场\n`));

			arrPrint.push(util.sendDirective([0x1b, 0x64, 0x02]))

			//发送数据
			this.printInfo(arrPrint)
		},

		//发送数据
		sendStr: function (bufferstr, success, failed) {
			var that = this
			wx.writeBLECharacteristicValue({
				deviceId: this._deviceId,
				serviceId: this._serviceId,
				characteristicId: this._characteristicId,
				value: bufferstr,
				success: function (res) {
					success(res)
					this.$http
						.ajax({
							url: '/Order/updateVisitStatus',
							params: {
								adminId: uni.getStorageSync('userInfo').id,
								visitStatus: '2',
								id
							}
						})
						.then((res) => {
							this.$api.msg('打印成功')
							if (res.code == 200) {
								this.orderList = []
								this.isfetch = false
								this.page = 1
								this.loadStatus = 'more'
								this.getOrderList()
							}
						})
				},
				failed: function (res) {
					fail(res)
					console.log('数据发送失败:' + JSON.stringify(res))
				},
				complete: function (res) {
					console.log('发送完成:' + JSON.stringify(res))
				}
			})
		},
		//遍历发送数据
		printInfo: function (arr) {
			var tthis = this
			if (arr.length > 0) {
				this.sendStr(
					arr[0],
					function (success) {
						arr.shift()
						tthis.printInfo(arr)
					},
					function (error) {
						console.log(error)
					}
				)
			}
		},
		//获取蓝牙设备所有服务(service)
		getBLEDeviceServices(deviceId) {
			wx.getBLEDeviceServices({
				deviceId,
				success: (res) => {
					for (let i = 0; i < res.services.length; i++) {
						if (res.services[i].isPrimary) {
							this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
							return
						}
					}
				},
				fail: (res) => {
					console.log('获取蓝牙服务失败：' + JSON.stringify(res))
				}
			})
		},

		//获取蓝牙设备某个服务中所有特征值(characteristic)
		getBLEDeviceCharacteristics(deviceId, serviceId) {
			wx.getBLEDeviceCharacteristics({
				deviceId,
				serviceId,
				success: (res) => {
					for (let i = 0; i < res.characteristics.length; i++) {
						let item = res.characteristics[i]
						if (item.properties.read) {
							wx.readBLECharacteristicValue({
								deviceId,
								serviceId,
								characteristicId: item.uuid
							})
						}

						if (item.properties.write) {
							this.canWrite = true
							this._deviceId = deviceId
							this._serviceId = serviceId
							this._characteristicId = item.uuid
							this.printBarcode()
						}

						if (item.properties.notify || item.properties.indicate) {
							wx.notifyBLECharacteristicValueChange({
								deviceId,
								serviceId,
								characteristicId: item.uuid,
								state: true
							})
						}
					}
				},
				fail(res) {
					console.error('获取特征值失败：', res)
				}
			})

			// 操作之前先监听，保证第一时间获取数据
			// wx.onBLECharacteristicValueChange((characteristic) => {
			// 	const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
			// 	const data = {}
			// 	if (idx === -1) {
			// 		data[`chs[${this.data.chs.length}]`] = {
			// 			uuid: characteristic.characteristicId,
			// 			value: ab2hex(characteristic.value)
			// 		}
			// 	} else {
			// 		data[`chs[${idx}]`] = {
			// 			uuid: characteristic.characteristicId,
			// 			value: ab2hex(characteristic.value)
			// 		}
			// 	}
			// 	// data[`chs[${this.data.chs.length}]`] = {
			// 	//   uuid: characteristic.characteristicId,
			// 	//   value: ab2hex(characteristic.value)
			// 	// }
			// 	this.setData(data)
			// })
		},
		//连接低功耗蓝牙设备
		createBLEConnection(e) {
			var that = this

			wx.createBLEConnection({
				deviceId: that.deviceId,
				success: (res) => {
					that.getBLEDeviceServices(that.deviceId)

					// setTimeout(function() {
					// 	//要延时1s
					// 	that.writeBLECharacteristicValue();

					// }, 1000) //延迟时间 这里是2秒
				},
				fail: (res) => {
					this.$api.msg('蓝牙连接失败')
				}
			})
			that.stopBluetoothDevicesDiscovery()
		},
		// 停止
		stopBluetoothDevicesDiscovery() {
			wx.stopBluetoothDevicesDiscovery()
		},
		// 寻找到新设备的事件的回调函数
		onBluetoothDeviceFound() {
			wx.onBluetoothDeviceFound((res) => {
				res.devices.forEach((device) => {
					if (!device.name && !device.localName) {
						return
					}
					if (this.deviceId) {
						return
					}

					if (device.name == 'Qsprinter' || device.localName == 'Qsprinter') {
						this.deviceId = device.deviceId
						this.createBLEConnection()
					}
					// const foundDevices = this.devices
					// const idx = inArray(foundDevices, 'deviceId', device.deviceId)
					// const data = {}
					// if (idx === -1) {
					// 	data[`devices[${foundDevices.length}]`] = device
					// } else {
					// 	data[`devices[${idx}]`] = device
					// }
					// this.setData(data)
				})
			})
		},
		//开始搜寻附近的蓝牙外围设备
		startBluetoothDevicesDiscovery() {
			if (this._discoveryStarted) {
				return
			}
			console.log('开始搜寻附近的蓝牙外围设备')
			this._discoveryStarted = true
			wx.startBluetoothDevicesDiscovery({
				allowDuplicatesKey: true,
				success: (res) => {
					this.onBluetoothDeviceFound()
				},
				fail: (res) => {
					this.$api.msg('蓝牙初始化失败')
				}
			})
		},
		//初始化蓝牙模块
		openBluetoothAdapter() {
			wx.openBluetoothAdapter({
				success: (res) => {
					this.startBluetoothDevicesDiscovery()
				},
				fail: (res) => {
					if (res.errCode === 10001) {
						wx.onBluetoothAdapterStateChange(function (res) {
							if (res.available) {
								this.startBluetoothDevicesDiscovery()
							}
						})
					}
				}
			})
		},
		toArr(str) {
			if (!str) {
				return []
			} else {
				return str.split(',')
			}
		},
		changeTab(status) {
			this.tabName = status
			if (status === '任务大厅') {
				this.orderState = '0'
			} else {
				this.orderState = '999'
			}
			this.isfetch = false
			this.page = 1
			this.loadStatus = 'more'
			this.getOrderList()
		},

		changeTab2(key) {
			this.current2 = this.l2Tabs.findIndex((v) => v === key)
			this.isfetch = false
			this.page = 1
			this.loadStatus = 'more'
			this.getOrderList()
		},
		getOrderList() {
      this.orderList = []
			this.$http
				.ajax({
					url: '/Order/selectByVisit',
					params: {
						adminId: uni.getStorageSync('userInfo').id,
						visitStatus:
							this.orderState === '999'
								? String(this.current2 + 1)
								: this.orderState,
						page: this.page,
						limit: 10
					}
				})
				.then((res) => {
					this.isfetch = true
					if (res.code == 0) {
						if (res.data.length < 10) {
							this.loadStatus = 'noMore'
						}
						if (this.page > 1) {
							this.orderList = this.orderList.concat(res.data)
						} else {
							this.orderList = res.data
						}
					} else {
						this.orderList = []
						this.loadStatus = 'noMore'
						this.$api.msg(res.msg)
					}
				})
		}
	}
}
</script>

<style scoped lang="scss">
.tip-box {
	width: 750rpx;
	background: #ffffff;
	padding: 34rpx 20rpx 68rpx;
	border-radius: 30rpx 30rpx 0 0;

	.box-t {
		padding: 0 35rpx;

		.title {
			position: relative;
		}
		.title::before {
			width: 6rpx;
			height: 32rpx;
			background: #3063d9;
			position: absolute;
			left: -16rpx;
			top: 6rpx;
			content: '';
		}
		.f-justifyB {
			margin-bottom: 30rpx;
		}
	}
	.btn {
		width: 710rpx;
		height: 100rpx;
		background: #3063d9;
		border-radius: 20rpx;
		margin-top: 10rpx;
	}
}

.goods-item {
	width: 750rpx;
	background: #ffffff;
	margin-top: 30rpx;
	position: relative;
	padding: 0 32rpx;
	margin-left: 15rpx;
	margin-right: 15rpx;
	.item-top {
		padding: 28rpx 0;

		.top-item {
			width: 82rpx;
			height: 32rpx;
			background: #4082ff;
			border-radius: 18rpx;
			font-size: 24rpx;
			line-height: 32rpx;
			color: #ffffff;
			text-align: center;
			margin: 10rpx 10rpx 0 0;
		}
	}

	.item-img {
		width: 160rpx;
		height: 160rpx;
	}

	.item-bottom {
		padding: 30rpx 0;
		border-top: 2rpx solid #aaaaaa;
	}

	.code-btn {
		width: 180rpx;
		height: 60rpx;
		background: #4082ff;
		border-radius: 32rpx;
		font-size: 28rpx;
		line-height: 60rpx;
		color: #ffffff;
		text-align: center;
	}
}

.container {
	padding: 0;
}
.top-title {
	font-size: 26rpx;
	margin-top: 15rpx;
}
.firsttop {
	display: flex;
	justify-content: space-between;

	font-size: 26rpx;
	// .firsttop-title{
	// 	flex: 1;
	// }
}
.bottom-column {
	display: flex;
	justify-content: flex-end;
	.top-jiedan {
		border-radius: 8rpx;
		padding-top: 13rpx;
		padding-bottom: 13rpx;
		padding-left: 80rpx;
		padding-right: 80rpx;
		background-color: #3063d9;
		color: white;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
		font-size: 28rpx;
	}
}
</style>
